# !/usr/bin/env python
#
# Copyright 2008 CPedia.com.
#
# New portions Copyright 2009, 2010 Rob Stenzinger 
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'Ping Chen, Rob Stenzinger'


import os
import re
import logging
import datetime
import simplejson
import wsgiref.handlers

from google.appengine.api import datastore
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.api import images
from google.appengine.ext import db

import model
from model import Archive,Weblog,WeblogReactions,Images,Tag,Feeds,Flash

import authorized
import util


from google.appengine.api import images


class Flash (webapp.RequestHandler):
    def get(self, flash_id):
        flash_id = flash_id.replace(".swf","")        
        flash = db.get(flash_id)        
        #flash = Flash().all().filter('filename =', filename).fetch(1)
        if flash.swf:
            self.response.headers["Content-Type"] = 'application/x-shockwave-flash'
            self.response.out.write(flash.swf)
        else:
            self.response.out.write("")
            
class ImageREST (webapp.RequestHandler):
    def get(self, image_id):
        image_id = image_id.replace(".png","")
        image_id = image_id.replace(".jpg","")        
        image = db.get(image_id)
        if image.image:
          #self.response.clear()
          self.response.headers['Content-Type'] = 'image/png' #detect_mime_from_image_data(image)
          self.response.out.write(image.image)
          #self.response.clear()
        else:
          self.response.out.write("No image")      

class ImageEpisode (webapp.RequestHandler):
    def get(self, image_params):
        #print image_params
        #restParameters = self.request.path.split("/")
        blog = Weblog.all()
        blog.filter("permalink =", image_params)
        #blog_result = None
        try:
            blog_result = blog.fetch(1)[0]
            #print blog_result
            #print blog_result.json_document
            episode_images = []
            #search1 = re.findall(r'''src=\\"/(\S)''', blog_result.json_document)
            search1 = re.findall(r'''src=\\"/(\S+)''', blog_result.json_document)
            #print search1
            search2 = re.findall(r"""src='/(\S+)""", blog_result.json_document)
            #print search2
            episode_images.extend(search1)
            episode_images.extend(search2)
            current_image_name = episode_images[0]
            current_image_name = current_image_name.replace("rpc/img/","")
            current_image_name = current_image_name.replace("\\","")
            current_image_name = current_image_name.replace("\"","")
            current_image_name = current_image_name.replace("\'","")
            if current_image_name.find(">") > -1:
                current_image_name = current_image_name[0:current_image_name.find(">")]

            current_image_name = current_image_name.replace(">","")
            current_image_name = current_image_name.replace(",","")
            #print current_image_name
            image = db.get(current_image_name)
            if image.image:
                #self.response.clear()
                self.response.headers["Content-Type"] = 'image/png' #detect_mime_from_image_data(image)
                self.response.out.write(image.image)
                #self.response.clear()
            else:
                self.response.out.write("No image")            
        except Exception, e:
            print "error in imageepisode:"
            print e
            
        return None

class ImageEpisodeThumb (webapp.RequestHandler):
    config = None
    def get(self, image_params):
        if self.config is None:
            self.config = util.get_config()

        #print image_params
        #restParameters = self.request.path.split("/")
        blog = Weblog.all()
        blog.filter("permalink =", image_params)
        #blog_result = None
        success = False
        blog_result = blog.fetch(1)[0]
        try:            
            #print blog_result
            #print blog_result.json_document
            episode_images = []
            #search1 = re.findall(r'''src=\\"/(\S)''', blog_result.json_document)
            search1 = re.findall(r'''src=\\"/(\S+)''', blog_result.json_document)
            #print search1
            search2 = re.findall(r"""src='/(\S+)""", blog_result.json_document)
            #print search2
            episode_images.extend(search1)
            episode_images.extend(search2)
            #print episode_images
            current_image_name = episode_images[0]
            current_image_name = current_image_name.replace("rpc/img/","")
            current_image_name = current_image_name.replace("\\","")
            current_image_name = current_image_name.replace("\"","")
            current_image_name = current_image_name.replace("\'","")
            if current_image_name.find(">") > -1:
                current_image_name = current_image_name[0:current_image_name.find(">")]
            
            current_image_name = current_image_name.replace(">","")
            current_image_name = current_image_name.replace(",","")

            #print current_image_name
            
            if len(current_image_name) > 0:
                key_ = current_image_name + "_thumb__1"
                try:
                    thumbnail = memcache.get(key_)
                except Exception:
                    thumbnail = None
                    
                    
                thumbnail = None
                        
                if thumbnail is None:
                    db_image = db.get(current_image_name)
                
                    if db_image.image:
                        img = images.Image(db_image.image)
                        img.resize(width=100, height=100)                
                        #img.im_feeling_lucky()                
                        thumbnail = img.execute_transforms(output_encoding=images.PNG)                
                        memcache.add(key=key_, value=thumbnail, time=3600)
                    else:
                        self.response.out.write("No image")
                        
                if thumbnail is not None:
                    self.response.headers["Content-Type"] = 'image/png' #detect_mime_from_image_data(image)
                    self.response.out.write(thumbnail)
                    success = True               
        except Exception, e:
            #print "error in imageepisode:"
            #print e
            success = False

        if success == False:
            placeholder_image_name = ""
            if blog_result.entrytype == "comic":
                placeholder_image_name = "thumbnail_comic.png"
            elif blog_result.entrytype == "blog":
                placeholder_image_name = "thumbnail_blog.png"
            elif blog_result.entrytype == "page":
                placeholder_image_name = "thumbnail_page.png"
            elif blog_result.entrytype == "audio":
                placeholder_image_name = "thumbnail_audio.png"
            elif blog_result.entrytype == "video":
                placeholder_image_name = "thumbnail_video.png"
            
            if len(placeholder_image_name) == 0:
                placeholder_image_name = "thumbnail_blog.png"
                
            asset, header = util.fetch_asset(placeholder_image_name, self.config["template_theme_directory"])
            self.response.clear()
            self.response.headers["Content-Type"] = header
            self.response.out.write(asset)          
               
        return None
            
          
class ImageLocal (webapp.RequestHandler):
    def get(self, image_filename):
        image = db.get(image_id)
        if image.image:
          #self.response.clear()
          self.response.headers['Content-Type'] = 'image/png' #detect_mime_from_image_data(image)
          self.response.out.write(image.image)
          #self.response.clear()
        else:
          self.response.out.write("No image")          
      
class ImageByFileNameREST(webapp.RequestHandler):      
    def get(self, image_name):
        image_served = False
        if image_name:            
            try:
                if image_name.find(".") > -1:
                    images = Images.all().filter('filename =',image_name).fetch(1)
                    if images != []:
                        if images[0].image:
                          respond_image(self, images[0].image)
                          #image_served = True
            except:
                pass
            
            if image_served is False: 
                image = db.get(image_name)
                if image:
                  respond_image(self, image)
                  #image_served = True
              
def respond_image(request_handler_ref, image):
    request_handler_ref.response.headers["Content-Type"] = 'image/png' #detect_mime_from_image_data(image)
    request_handler_ref.response.out.write(image)
            
def no_image(request_handler_ref):
    request_handler_ref.response.out.write("No image")

class UploadImage (webapp.RequestHandler):
    @authorized.role('admin')
    def post(self):
        images = Images()
        img = self.request.get("fileToUpload")

        try:
            #img_test = images.Image(img) 
            images.image = db.Blob(img)
            images.uploader = users.GetCurrentUser()
            key = images.put()
        except Exception, e:
            self.response.out.write( '{status:"An Error Occurred uploading the image."}')
            return
        self.response.out.write('{status:"UPLOADED IMAGE",file_url:"/rpc/img/%s"}' % (key))

class UploadFlash (webapp.RequestHandler):
    @authorized.role('admin')
    def post(self):
        store_file = model.Flash()
        img = self.request.get("fileToUpload")
        
        if not img:
            self.response.out.write( '{status:"Please select your Flash file."}')
            return
        
        try:
            store_file.swf = db.Blob(img)
            store_file.uploader = users.GetCurrentUser()
            key = store_file.put()
        except Exception, e:
            self.response.out.write( '{status:"An Error Occurred uploading the Flash file."}')
            return
        self.response.out.write('{status:"UPLOADED FLASH",file_url:"/rpc/flash/%s"}' % (key))

      
      
      

